package com.itheima.localdatatimeutil;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MyLocalDateTimeUtil {
    public MyLocalDateTimeUtil() {
    }

    //默认格式 "yyyy-MM-dd HH:mm:ss"将日期对象格式化为字符串
    public static String localDateTimeToString(LocalDateTime localDateTime) {
        return localDateTimeToString(localDateTime, null);
    }

    //按照指定格式将日期对象转化为字符串
    public static String localDateTimeToString(LocalDateTime localDateTime, String pattern) {
        if (pattern == null || "".equals(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        String str = formatter.format(localDateTime);
        return str;
    }

    //按照指定格式将字符串解析为日期对象
    public static LocalDateTime stringToLocalTimeDate(String dateStr, String pattern) {
        if (pattern == null || "".equals(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime parse = LocalDateTime.parse(dateStr, formatter);
        return parse;
    }

    //按照默认格式将字符串解析为日期对象
    public static LocalDateTime stringToLocalTimeDate(String dateStr) {
        return stringToLocalTimeDate(dateStr, null);
    }

    public static long millisecondBetween(LocalDateTime t1, LocalDateTime t2) {
        Duration between = Duration.between(t1, t2);
        long millis = between.toMillis();
        long abs = Math.abs(millis);
        return abs;
    }
}
